package utils

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"strconv"
	"time"
)

func CreateToken(id int) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Add(time.Hour * time.Duration(3000)).Unix() //过期时间
	claims["iat"] = time.Now().Unix()                                      //设置token时间
	claims["id"] = strconv.Itoa(id)
	token.Claims = claims
	return token.SignedString([]byte("house"))
}

func CheckToken(tokenString string) (int64, error) {
	id := int64(0)
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method")
		}
		return []byte("house"), nil
	})
	if err != nil {
		return 0, err
	}
	claims, _ := token.Claims.(jwt.MapClaims)
	id = int64(claims["id"].(float64))
	return id, nil
}
